package com.cn.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.cn.gmall.common.mqconst.MqConst;
import com.cn.gmall.model.enums.PaymentStatus;
import com.cn.gmall.model.enums.ProcessStatus;
import com.cn.gmall.model.order.OrderInfo;
import com.cn.gmall.model.payment.PaymentInfo;
import com.cn.gmall.order.service.OrderService;
import com.cn.gmall.payment.client.PaymentFeignClient;
import com.google.common.collect.Ordering;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.checkerframework.common.value.qual.StringVal;
import org.springframework.amqp.core.Message;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;


@Component
public class OrderReceiver {
    @Autowired
    private OrderService orderService;
    @Resource
    private PaymentFeignClient paymentFeignClient;

    /***
     * 库存扣减结果消费
     * @param mapJson
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void stockProcessResult(String mapJson, Message message, Channel channel) {
        try {
//   接收发送的信息数据
            if (!StringUtils.isEmpty(mapJson)) {
                //        发消息用的  JSON.toJSONString(map)   /  Map<String, Object> map = new HashMap<>();
                Map<String, Object> resultMap = JSON.parseObject(mapJson, Map.class);
                //       获取订单id
                String orderId = (String) resultMap.get("orderId");
                // 获取状态 DEDUCTED->意见库存  /    OUT_OF_STOCK -> 库存超卖
                if ("DEDUCTED".equals(resultMap.get("status"))) {
                    //      库存扣除 成功  -==> 更改订单状态
                    orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.WAITING_DELEVER);

                } else {
                    //                扣除失败 修改订单状态  并
                    //                1. 仓库互补
                    //                2. 通知补货
                    orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.STOCK_EXCEPTION);
                }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
//      通知运维 或 开发人员
        }
//       手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /****
     * 支付成功后 修改订单状态 + 发扣减库存消息
     * @param out_trade_no
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,durable = "true"),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void paySuccess(String out_trade_no, Message message, Channel channel) {
        try {
            if (!StringUtils.isEmpty(out_trade_no)) {
    //    查询 orderInfo  根据out_trade_no
                OrderInfo orderInfo = orderService.findOrderByOutTradeNo(out_trade_no);
                if (!ObjectUtils.isEmpty(orderInfo)) {
    //                修改订单状态
                    orderService.updateOrderStatus(orderInfo.getId(), ProcessStatus.PAID);
    //订单信息更行完成  通知库存进行更新(扣减库存)
                    orderService.sendOrderSatus(orderInfo.getId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    /***
     * 订单超时提交
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel) {
        try {                      //幂等性处理
            if (orderId != null) {
//-------------判断是否已经支付--------------------
                OrderInfo orderInfo = orderService.getOrderById(orderId);
                if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())) {
//----------------查询paymentInfo 是否存在！----------------
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    if (!ObjectUtils.isEmpty(paymentInfo) && "UNPAID".equals(paymentInfo.getPaymentStatus())){
//------------------查看支付宝-->是否有交易记录-(扫码之后 就会生成支付宝的记录)-------------
                        Boolean flag = paymentFeignClient.checkPayment(orderId);
                        if (flag){
//-----------------------有记录--->调用支付宝关闭接口  扫码未支付 订单付款----------------
                            Boolean result = paymentFeignClient.closePay(orderId);
                            if (result) {
//---------------------------------支付宝关闭订单成功--->关闭本地 修改本地订单状态------------------
                                //    关闭订单
                                orderService.execExpiredOrder(orderId,"2");

                            }else {
                                //  result = false; 表示付款！
                                //  说明已经付款了！ 正常付款成功都会走异步通知！
                            }

                        }else {
                            //  没有交易记录，不需要关闭支付！  需要关闭orderInfo， paymentInfo
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    }else {
                        //  只关闭订单orderInfo！
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//            消息不能正常消费 发短息找运维
        }

        //消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
